// pages/my-jobs/my-jobs.js
Page({
  data: {
    jobs: [],
    loading: false,
    hasMore: true,
    page: 0,
    size: 10,
    activeTab: 0,
    tabs: [
      { key: '', label: '全部' },
      { key: 'PUBLISHED', label: '已发布' },
      { key: 'ACTIVE', label: '招聘中' },
      { key: 'COMPLETED', label: '已完成' },
      { key: 'CLOSED', label: '已关闭' }
    ]
  },

  onLoad() {
    this.checkLoginAndRole();
  },

  onShow() {
    this.checkLoginAndRole();
  },

  // 检查登录状态和用户角色
  checkLoginAndRole() {
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');
    
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/profile/profile'
        });
      }, 1500);
      return;
    }

    if (userInfo && userInfo.role !== 'EMPLOYER') {
      wx.showToast({
        title: '仅限用工方使用',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }

    this.loadMyJobs(true);
  },

  // 加载我的岗位列表
  loadMyJobs(refresh = false) {
    if (this.data.loading) return;

    this.setData({ loading: true });

    const page = refresh ? 0 : this.data.page;
    const token = wx.getStorageSync('token');
    const status = this.data.tabs[this.data.activeTab].key;

    wx.request({
      url: 'http://localhost:8080/api/employer/jobs',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      data: {
        page: page,
        size: this.data.size,
        status: status
      },
      success: (res) => {
        if (res.data.code === 200) {
          const newJobs = res.data.data.content || [];
          this.setData({
            jobs: refresh ? newJobs : [...this.data.jobs, ...newJobs],
            hasMore: !res.data.data.last,
            page: page + 1
          });
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        // 模拟数据
        const mockJobs = [
          {
            id: 1,
            title: '餐厅服务员',
            jobType: 'PART_TIME',
            salary: 25,
            salaryType: 'HOURLY',
            location: '北京市朝阳区',
            description: '负责餐厅日常服务工作',
            requiredWorkers: 5,
            appliedCount: 8,
            status: 'PUBLISHED',
            publishTime: '2024-01-10 10:00:00'
          },
          {
            id: 2,
            title: '快递配送员',
            jobType: 'FULL_TIME',
            salary: 6000,
            salaryType: 'MONTHLY',
            location: '北京市海淀区',
            description: '负责快递配送工作',
            requiredWorkers: 3,
            appliedCount: 12,
            status: 'ACTIVE',
            publishTime: '2024-01-08 14:30:00'
          }
        ];

        this.setData({
          jobs: refresh ? mockJobs : [...this.data.jobs, ...mockJobs],
          hasMore: false,
          page: page + 1
        });
      },
      complete: () => {
        this.setData({ loading: false });
        if (refresh) {
          wx.stopPullDownRefresh();
        }
      }
    });
  },

  // 切换标签
  switchTab(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      activeTab: index,
      page: 0,
      jobs: []
    });
    this.loadMyJobs(true);
  },

  // 跳转到岗位详情
  goToJobDetail(e) {
    const jobId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/job-detail/job-detail?id=${jobId}`
    });
  },

  // 查看申请者列表
  viewApplicants(e) {
    const jobId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/job-applicants/job-applicants?jobId=${jobId}`
    });
  },

  // 编辑岗位
  editJob(e) {
    const jobId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/publish-job/publish-job?id=${jobId}&mode=edit`
    });
  },

  // 关闭岗位
  closeJob(e) {
    const jobId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '确认关闭',
      content: '确定要关闭这个岗位吗？关闭后将不再接收新的申请。',
      success: (res) => {
        if (res.confirm) {
          this.performCloseJob(jobId);
        }
      }
    });
  },

  // 执行关闭岗位
  performCloseJob(jobId) {
    const token = wx.getStorageSync('token');

    wx.request({
      url: `http://localhost:8080/api/employer/jobs/${jobId}/close`,
      method: 'PUT',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({
            title: '岗位已关闭',
            icon: 'success'
          });
          this.loadMyJobs(true);
        } else {
          wx.showToast({
            title: res.data.message || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '岗位已关闭',
          icon: 'success'
        });
        this.loadMyJobs(true);
      }
    });
  },

  // 格式化薪资显示
  formatSalary(job) {
    const { salary, salaryType } = job;
    let unit = '';
    switch (salaryType) {
      case 'HOURLY': unit = '/时'; break;
      case 'DAILY': unit = '/天'; break;
      case 'MONTHLY': unit = '/月'; break;
      default: unit = '';
    }
    return `${salary}元${unit}`;
  },

  // 格式化岗位类型
  formatJobType(type) {
    const typeMap = {
      'FULL_TIME': '全职',
      'PART_TIME': '兼职',
      'TEMPORARY': '临时工',
      'INTERNSHIP': '实习'
    };
    return typeMap[type] || type;
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'DRAFT': '草稿',
      'PUBLISHED': '已发布',
      'ACTIVE': '招聘中',
      'PAUSED': '已暂停',
      'COMPLETED': '已完成',
      'CLOSED': '已关闭',
      'CANCELLED': '已取消'
    };
    return statusMap[status] || status;
  },

  // 获取状态颜色
  getStatusColor(status) {
    const colorMap = {
      'DRAFT': '#8c8c8c',
      'PUBLISHED': '#1890ff',
      'ACTIVE': '#52c41a',
      'PAUSED': '#fa8c16',
      'COMPLETED': '#52c41a',
      'CLOSED': '#8c8c8c',
      'CANCELLED': '#f5222d'
    };
    return colorMap[status] || '#8c8c8c';
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadMyJobs(true);
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMyJobs(false);
    }
  },

  // 跳转到发布岗位页面
  goToPublish() {
    wx.navigateTo({
      url: '/pages/publish-job/publish-job'
    });
  }
});
